// pages/comment/comment.js
import {
  getCommentsById
} from "../../utils/util_joke"
const db = wx.cloud.database();
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    commentList: [],
    count: 30,
    page: 1,
    total: 0,
    commentId: "",
    content: "",
    currentTime: parseInt(new Date().valueOf() / 1000)
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    let commentId = options.id;
    let {
      count,
      page
    } = this.data
    let that = this;
    getCommentsById(commentId, count, page, function (res) {
      that.setData({
        commentList: res.items.reverse(),
        total: res.total,
        commentId: options.id
      })
      console.log(that.data.commentList)
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.setData({
      count: this.data.total > this.data.count + 10 ? this.data.count + 10 : this.data.count
    })
    let {
      count,
      page,
      commentId
    } = this.data;
    let that = this;
    getCommentsById(commentId, count, page, function (res) {
      that.setData({
        commentList: res.items.reverse(),
      })
      console.log(res.items);
    })
  },


  addComment: function () {
    var that = this;
    let user = {
      login: app.globalData.userInfo.nickName,
      medium: app.globalData.userInfo.avatarUrl,
    }
    wx.cloud.callFunction({
        // 云函数名称
        name: 'addComment',
        // 传给云函数的参数
        data: {
          id: that.data.commentId,
          content: that.data.content,
          like_count: 0,
          user: user,
          created_at: new Date(),
        }

      }).then(res => {
        console.log(res);
       
          setTimeout(function () {
            wx.pageScrollTo({
              scrollTop: 0,
              complete(co) {
                console.log(co)
              }
            })
          }, 100)


        return db.collection('comments').doc(res.result._id).get()
      })
      .then(res => {
        console.log(res.data) // res.data 包含该记录的数据
        this.data.commentList.unshift(res.data);
        this.setData({
          commentList: this.data.commentList
        })
        console.log()
      })
      .catch(error => {
        console.log(error)
      })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})